#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "datahandler.h"
#include "plotform.h"
#include "QsLog/QsLog.h"
#include "ruanzhuui.h"

#include <QTextStream>
#include <QMessageBox>
#include <QSerialPortInfo>
#include <QDebug>
#include <QTime>
#include <QTimer>
#include <QFile>
#include <QThread>
#include <QProcess>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget),
    dataHandler(new DataHandler()),  // 创建 DataHandler 对象
    serialPort(new SerialPort(dataHandler, this)),  // 将指向 DataHandler 对象的指针传递给 SerialPort
    m_turnTable(nullptr),
    m_timer(new QTimer),
    m_longtitude(999),
    m_latitude(999)
{
    ui->setupUi(this);
    serialPort->refreshSerialPorts(ui->SolarcomboBox);
    //初始化自动测量使用的QTimer
    initTimer();
    //格式化页面
    initForm();

}

Widget::~Widget()
{
    delete ui;
    delete serialPort;   // 释放 SerialPort 对象
    delete dataHandler;  // 释放 DataHandler 对象
}

void Widget::on_pushButton_connect_clicked()
{
    QString portName = ui->SolarcomboBox->currentText();
    // 检查串口是否已打开
    if (serialPort->isOpen()) {
        QMessageBox::information(this, tr("连接已打开"), tr("串口已经打开"));
        return; // 退出函数，避免重复操作
    }
    bool success = serialPort->openPort(portName);

    if (success) {
        QLOG_INFO()<<"[串口操作]：打开串口成功";
        QMessageBox::information(this, tr("连接成功"), tr("串口已打开"));
    } else {
        QLOG_INFO()<<"[串口操作]：打开串口失败";
        QMessageBox::critical(this, tr("连接失败"), tr("无法打开串口"));
    }
}

void Widget::on_pushButton_close_clicked()
{
    serialPort->closePort();
    QLOG_INFO()<<"[串口操作]：关闭串口";
    QMessageBox::information(this, tr("关闭成功"), tr("串口已关闭"));
}

// 刷新按钮的槽函数
void Widget::on_pushButton_Refresh_clicked()
{
     serialPort->refreshSerialPorts(ui->SolarcomboBox);//刷新串口
}

// 数据处理完成后的槽函数
void Widget::onDataProcessed(const CommandResponse &responseData)
{
    // 获取当前时间并格式化为 "hhmmss"
    QString currentTime = QTime::currentTime().toString("hh:mm:ss");

    // 将时间、"收到:" 和处理后的数据拼接在一起
    QString finalData("[收到太阳辐射计数据:]");

    // 拼接响应数据
    finalData += responseData.handshakeSignal.isEmpty() ? "" :responseData.handshakeSignal + " ";
    finalData += responseData.deviceVersion.isEmpty() ? "" : responseData.deviceVersion + " ";
    // 调用 parseFilterTypes 函数解算 filterTypes
    finalData += responseData.filterTypes.isEmpty() ? "" :dataHandler->parseFilterTypes(responseData.filterTypes) + " ";

    finalData += responseData.autoMeasureResponse.isEmpty() ? "" : responseData.autoMeasureResponse + " ";
    finalData += responseData.readMeasureResponse.isEmpty() ? "" : responseData.readMeasureResponse + " ";
    finalData += responseData.unknownCommand.isEmpty() ? "" : responseData.unknownCommand + " ";
    finalData.append("\n");
    QLOG_INFO()<<finalData;
    finalData = currentTime.append(finalData);
    ui->textEdit->append(finalData);


}

void Widget::initTimer()
{
    m_timer->setInterval(60000);
    connect(m_timer, &QTimer::timeout, this, [=](){
        //每次测量前，都进行判断
        if(checkSunPosition()){
            serialPort->readAutoMeasurementData();
            QThread::msleep(500);
            serialPort->startAutoMeasurement();
        }
    });
}

void Widget::initForm()
{
    //设置经纬度
    connect(ui->pushButton_setLonLat, &QPushButton::clicked, this, [=](){
        bool ok = false;
        double latitude = ui->lineEdit_latitude->text().toDouble(&ok);
        if(!ok || latitude < 0 || latitude > 90){
            QMessageBox::critical(this, "设置经纬度失败", "纬度格式错误，纬度范围0~90");
            return;
        }
        double longtitude = ui->lineEdit_longitude->text().toDouble(&ok);
        if(!ok || longtitude < 0 || longtitude > 180){
            QMessageBox::critical(this, "设置经纬度失败", "经度格式错误，经度范围0~180");
            return;
        }
        m_latitude = latitude;
        m_longtitude = longtitude;
        QString message = QString("设置经纬度成功, 经度：%1， 纬度：%2").arg(QString::number(longtitude)).arg(QString::number(latitude));
        QMessageBox::information(this, "设置经纬度成功", message);
        return;
    });

    //画图光学厚度的页面
    connect(ui->pushButton_plot, &QPushButton::clicked, this, [=](){
        PlotForm* plotform = new PlotForm;
        plotform->show();
    });

    //设置textEdit最大显示行数
    ui->textEdit->document()->setMaximumBlockCount(500);

    //数据解析完成后，存入日志文件
    connect(dataHandler, &DataHandler::structDateHandle, this, &Widget::onDataProcessed);

    //开始/结束自动测量按钮
    connect(ui->pushButton_autoObserve, &QPushButton::clicked, this, &Widget::Slots_autoObserve);
}

void Widget::on_pushButton_handshake_clicked()
{
    // 发送握手信号命令
    serialPort->sendHandshakeCommand();
}
#include <QDir>

void Widget::on_pushButton_version_clicked()
{
    // 发送查询设备版本号命令
    //serialPort->sendDeviceVersionQuery();

    // if(nullptr == m_turnTable){
    //     m_turnTable = new ruanzhuUI();
    // }
    // m_turnTable->show();

    qDebug()<<"work dir "<<QDir::currentPath();

    QProcess turnTableProcess;

    turnTableProcess.startDetached("\"./untitled.exe\"");


}

void Widget::on_pushButton_filter_clicked()
{
    // 发送查询滤光片类型命令
    serialPort->sendFilterTypesQuery();
}

void Widget::on_pushButton_startMeasurement_clicked()
{

    // 发送启动测量数据命令
    serialPort->startAutoMeasurement();

}

void Widget::on_pushButton_readMeasurement_clicked()
{
    // 发送读取自动测量数据命令
    serialPort->readAutoMeasurementData();
}

void Widget::Slots_autoObserve()
{
    if(ui->pushButton_autoObserve->text() == "开始自动测量"){
        if(!serialPort->isOpen()){
            QMessageBox::critical(this, tr("开启自动测量失败"), tr("串口未打开"));
            return;
        }

        if(m_latitude == 999 || m_longtitude == 999){
            QMessageBox::critical(this, "开启自动测量失败", "经纬度未设置");
            return;
        }

        //经纬度正确，串口打开，可以开始自动测量
        if(checkSunPosition()){
            //获取最新一条数据
            serialPort->readAutoMeasurementData();
            //QThread::msleep(500);
            //开始观测，观测期间无响应
            serialPort->startAutoMeasurement();
        }
        m_timer->start();
        ui->pushButton_autoObserve->setText("结束自动测量");
    }else{
        m_timer->stop();
        ui->pushButton_autoObserve->setText("开始自动测量");
    }
}

bool Widget::checkSunPosition()
{
    SunPosition sunPosition;
    QDateTime dt = QDateTime::currentDateTime();
    std::pair position = sunPosition.calculateSunPosition(m_longtitude, m_latitude, dt.date().year(), dt.date().month(), dt.date().day(), dt.time().hour(), dt.time().minute(), dt.time().second());
    double heightAngle = position.first* 180.0 / M_PI;
    double azimuth = position.second* 180.0 / M_PI;
    // 将结果转换为角度制
    QString logStr = QString("%1 [计算太阳高度角]当前高度角为:%2, 当前方位角：%3")
                         .arg(QTime::currentTime().toString("HH:mm:ss"))
                            .arg(QString::number(heightAngle))
                            .arg(QString::number(azimuth));
    QLOG_INFO()<<logStr;
    ui->textEdit->append(logStr);
    return (heightAngle >= 5.0);
}
